package com.sample.springbatch.service;

import com.sample.springbatch.model.User;
import com.sample.springbatch.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * JPA事物服务实现类
 *
 * @author zwg
 * @date 2019-04-18 10:14
 **/

@Service
public class JpaTransactionalServiceImpl implements IJpaTransactionalService {

    Logger logger = LoggerFactory.getLogger(JpaTransactionalServiceImpl.class);

    @Autowired
    UserRepository userRepository;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void methodB() {
        User user = userRepository.findById(1);
        user.setAge(user.getAge()+1);
        userRepository.save(user);
        User user1 = userRepository.findById(1);
        logger.info("methodB  before:{} after:{}",user,user1);
        try{
            methodC();
        }catch (Exception e){
            logger.error("",e);
        }
        throw new RuntimeException("exception");

    }

    @Override
    @Transactional
    public void methodC() {
        User user = userRepository.findById(1);
        user.setAge(user.getAge()+1);
        userRepository.save(user);
        User user1 = userRepository.findById(1);
        logger.info("methodC  before:{} after:{}",user,user1);
        throw new RuntimeException("exception");
    }
}
